package com.canal.starter.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.lang.annotation.Annotation;
import java.util.*;

/**
 * @author chen.qian
 * @date 2018/3/16
 */
public class ApplicationContextUtils implements ApplicationContextAware {
    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        ApplicationContextUtils.applicationContext = applicationContext;
    }

    public static <T> T getBean(Class<T> clazz) {
        T bean = applicationContext.getBean(clazz);
        return bean;
    }

    public static <T> List<T> getBeansOfType(Class<T> clazz) {
        List<T> list = null;
        Map<String, T> map = applicationContext.getBeansOfType(clazz);
        if (map != null) {
            list = new ArrayList<>(map.values());
        }
        return list;
    }

    public static Map<String, Object> getBeansWithAnnotation(Class<? extends Annotation> anno) {
        Map<String, Object> map = applicationContext.getBeansWithAnnotation(anno);
        return map;
    }
}